Requirement already satisfied: openpyxl in c:\users\shuos\anaconda3\lib\site-packages (3.1.2)
Requirement already satisfied: et-xmlfile in c:\users\shuos\anaconda3\lib\site-packages (from openpyxl) (1.1.0)
Note: you may need to restart the kernel to use updated packages.
In [9]:
import pandas as pdimport matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npfrom pathlib import Pathimport pingouin as pgfrom lets_plot import*LetsPlot.setup_html(no_js=True)### You don't need to use these settings yourself### — they are just here to make the book look nicer!# Set the plot style for prettier charts:plt.style.use("https://raw.githubusercontent.com/aeturrell/core_python/main/plot_style.txt")
# Plot the datafig, ax = plt.subplots()df.plot(ax=ax)ax.set_title("Average contributions to the public goods game: Without punishment")ax.set_ylabel("Average contribution")ax.set_xlabel("Round");
<>:2: SyntaxWarning: invalid escape sequence '\i'
<>:2: SyntaxWarning: invalid escape sequence '\i'
C:\Users\shuos\AppData\Local\Temp\ipykernel_6528\951372428.py:2: SyntaxWarning: invalid escape sequence '\i'
"E:\教育管理\it\作业\doing-economics-datafile-working-in-excel-project-2.xlsx",
c:\Users\shuos\anaconda3\Lib\site-packages\openpyxl\worksheet\_read_only.py:81: UserWarning: Unknown extension is not supported and will be removed
for idx, row in parser.parse():
In [32]:
test_data = {"City A": [14.1, 14.1, 13.7],"City B": [11.0, 12.6, 12.1],}# Original dataframetest_df = pd.DataFrame.from_dict(test_data)# A copy of the dataframetest_copy = test_df.copy()# A pointer to the dataframetest_pointer = test_dftest_pointer.iloc[1, 1] =99
C:\Users\shuos\AppData\Local\Temp\ipykernel_6528\3801786469.py:2: FutureWarning: The provided callable <function mean at 0x000001AAD3ADF740> is currently using DataFrame.mean. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string "mean" instead.
mean_p_c = data_p.agg(np.mean, axis=1)
In [18]:
fig, ax = plt.subplots()mean_n_c.plot(ax=ax, label="Without punishment")mean_p_c.plot(ax=ax, label="With punishment")ax.set_title("Average contributions to the public goods game")ax.set_ylabel("Average contribution")ax.legend();
Q:Describe any differences and similarities you see in the mean contribution over time in both experiments. A:The unpunished experiments show a downward trend, and the trend for the punished experiments is generally slowly rising. Both have the fastest rate of decline in the period 9.
In [19]:
partial_names_list = ["F. Kennedy", "Lennon", "Maynard Keynes", "Wayne"]["John "+ name for name in partial_names_list]
['John F. Kennedy', 'John Lennon', 'John Maynard Keynes', 'John Wayne']
In [20]:
['John F. Kennedy', 'John Lennon', 'John Maynard Keynes', 'John Wayne']
['John F. Kennedy', 'John Lennon', 'John Maynard Keynes', 'John Wayne']
In [21]:
# Create new dataframe with bars incompare_grps = pd.DataFrame( [mean_n_c.loc[[1, 10]], mean_p_c.loc[[1, 10]]], index=["Without punishment", "With punishment"],)# Rename columns to have 'round' in themcompare_grps.columns = ["Round "+str(i) for i in compare_grps.columns]# Swap the column and index variables around with the transpose function, ready for plotting (.T is transpose)compare_grps = compare_grps.T# Make a bar chartcompare_grps.plot.bar(rot=0);
Q:Calculate the standard deviation for Periods 1 and 10 separately, for both experiments. Does the rule of thumb apply? (In other words, are most values within two standard deviations of the mean?) A:Contributions without punishment,Period 1: standard deviation about 1.82. Period 10: standard deviation is about 2.03 Contributions with punishment:Period 1: standard deviation is about 3.30. Period 10: standard deviation is about 4.67
In [22]:
n_c = data_n.agg(["std", "var", "mean"], 1)n_c
std
var
mean
Period
1
2.020724
4.083325
10.578313
2
2.238129
5.009220
10.628398
3
2.329569
5.426891
10.407079
4
2.068213
4.277504
9.813033
5
2.108329
4.445049
9.305433
6
2.240881
5.021549
8.454844
7
2.136614
4.565117
7.837568
8
2.349442
5.519880
7.376388
9
2.413845
5.826645
6.392985
10
2.187126
4.783520
4.383769
In [23]:
p_c = data_p.agg(["std", "var", "mean"], 1)
In [24]:
fig, ax = plt.subplots()n_c["mean"].plot(ax=ax, label="mean")# mean + 2 standard deviations(n_c["mean"] +2* n_c["std"]).plot(ax=ax, ylim=(0, None), color="red", label="±2 s.d.")# mean - 2 standard deviations(n_c["mean"] -2* n_c["std"]).plot(ax=ax, ylim=(0, None), color="red", label="")for i inrange(len(data_n.columns)): ax.scatter(x=data_n.index, y=data_n.iloc[:, i], color="k", alpha=0.3)ax.legend()ax.set_ylabel("Average contribution")ax.set_title("Contribution to public goods game without punishment")plt.show();
# A lambda function accepting three inputs, a, b, and c, and calculating the sum of the squarestest_function =lambda a, b, c: a**2+ b**2+ c**2# Now we apply the function by handing over (in parenthesis) the following inputs: a=3, b=4 and c=5test_function(3, 4, 5)
fig, ax = plt.subplots()range_p.plot(ax=ax, label="With punishment")range_n.plot(ax=ax, label="Without punishment")ax.set_ylim(0, None)ax.legend()ax.set_title("Range of contributions to the public goods game")plt.show();